package com.ls.demo.tcp.config;

import com.ls.demo.tcp.handler.HeartbeatHandler;
import com.ls.demo.tcp.handler.VerChannelHandlerImpl;
import com.ls.demo.tcp.protocol.ByteToHexDecoder;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.socket.SocketChannel;
import io.netty.handler.timeout.IdleStateHandler;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.concurrent.TimeUnit;

/**
 * @author liShan
 * @date 2019/8/28 16:13
 */
@Component
public class TcpServerChannelInitializer extends ChannelInitializer<SocketChannel> {

    @Resource
    private VerChannelHandlerImpl verChannelHandler;

    @Resource
    private HeartbeatHandler heartbeatHandler;

    @Resource
    private TcpServerProperties tcpServerProperties;

    @Override
    protected void initChannel(SocketChannel ch){
        ch.pipeline()
                .addFirst("hexDecoder", new ByteToHexDecoder())
                .addLast("idleStateHandler", new IdleStateHandler(
                        tcpServerProperties.getReaderIdleTime(),
                        tcpServerProperties.getWriterIdleTime(),
                        tcpServerProperties.getAllIdleTime(),
                        TimeUnit.MILLISECONDS)
                )
                .addLast("heartbeatHandler", heartbeatHandler)
                .addLast("verification", verChannelHandler);
    }
}
